// src/main/java/org/csu/mybigpro/controller/CourseController.java
package org.csu.mybigpro.controller;

import org.csu.mybigpro.domain.Course;
import org.csu.mybigpro.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/courses")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @GetMapping
    public List<Course> list() {
        return courseService.list();
    }

    @GetMapping("/{id}")
    public Course get(@PathVariable Long id) {
        return courseService.getById(id);
    }

    @PostMapping
    public Course create(@RequestBody Course course) {
        courseService.save(course);
        System.out.println("新建课程成功，ID: " + course.getId()); // 保存后 course.id 会被自动填充
        return course; // 返回带真实 id 的课程对象
    }

    @PutMapping("/{id}")
    public boolean update(@PathVariable Long id, @RequestBody Course course) {
        course.setId(id); // 确保从路径变量获取的ID设置到对象中
        boolean success = courseService.updateById(course);
        if (success) {
            System.out.println("更新课程成功，ID: " + id);
        } else {
            System.err.println("更新课程失败，ID: " + id);
        }
        return success;
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用简化的删除方法，只删除课程本身
            boolean success = courseService.removeCourseAndRelationsById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "课程删除成功");
            } else {
                result.put("success", false);
                result.put("message", "课程删除失败，可能不存在");
            }
        } catch (Exception e) {
            System.err.println("删除课程时发生异常: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "删除课程时发生内部错误: " + e.getMessage());
        }
        return result;
    }
}